package com.example.leetcode;

/**
 * 动态规划
 * 最小路径和
 */
public class Demo0064 {
    public static void main(String[] args) {
        int [][] grid=new int[][]{{1,3,1},{1,5,1},{4,2,1}};
        minPathSum2(grid);
    }

    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n=grid[0].length;
        int [][] f=new int[m][n];
        f[0][0]=grid[0][0];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i-1>=0){
                    f[i][j]=f[i-1][j]+grid[i][j];
                }
                if (j-1>=0){
                    if (f[i][j]==0){
                        f[i][j]=f[i][j-1]+grid[i][j];
                    }else {
                        f[i][j]=Math.min(f[i][j-1]+grid[i][j],f[i][j]);
                    }
                }
            }
        }
        return f[m-1][n-1];
    }

    public static int minPathSum2(int[][] grid) {
        int m = grid.length;
        int n =grid[0].length;
        int[][] fun =new int[m+1][n+1];
        for (int i = 1; i < m+1; i++) {
            for (int j = 1; j < n+1; j++) {
                //1.考虑边界
                if (i==1 || j==1 ){
                    fun[i][j]=Math.max(fun[i-1][j]+grid[i-1][j-1],fun[i][j-1]+grid[i-1][j-1]);
                }else {
                    fun[i][j]=Math.min(fun[i-1][j]+grid[i-1][j-1],fun[i][j-1]+grid[i-1][j-1]);
                }
            }
        }
        return fun[m][n];
    }
}
